package com.pig4cloud.pig.iotData.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class OkHttpUtil {
	private static final ObjectMapper objectMapper=new ObjectMapper();

	// 默认超时时间
	private static final int DEFAULT_TIMEOUT = 60; // 60 seconds

	static {

		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); //设置java时间的序列化配置，这个要另外配置否则报错
//		objectMapper.registerModule(new JavaTimeModule());
		// 为 LocalDateTime 设置自定义序列化器
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		// 注册 JavaTimeModule
		JavaTimeModule javaTimeModule = new JavaTimeModule();
		javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
		// 注册模块
		objectMapper.registerModule(javaTimeModule);

		// 启用 WRITE_DATES_AS_TIMESTAMPS 功能
		objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
	}



	public static <T> Response postJsonBody(String url, T data, Map<String,String> headerMap) throws Exception {
		Request.Builder builder = new Request.Builder()
				.url(url);

		if(data!=null){
			// POST方式发送JSON数据
//		String json = "{\"username\":zhangsan,\"password\":\"123456\"}";

			String json = objectMapper.writeValueAsString(data);
			log.debug(json);
//		构建json请求头
			RequestBody body = RequestBody.create( json,MediaType.parse("application/json"));
			builder.post(body);
		}

		// 遍历Map并将头部信息添加到请求构建器中
		if(headerMap!=null){
			headerMap.forEach(builder::addHeader); //等价headerMap.forEach((key, value) -> builder.addHeader(key, value));
		}

		Request request = builder.build();

		OkHttpClient okHttpClient = new OkHttpClient.Builder()
				.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) // 连接超时时间
				.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)     // 读取超时时间
				.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) // 写入超时时间;
				.build();


		Call call = okHttpClient.newCall(request);
		Response response = null;
		response = call.execute();


		if (!response.isSuccessful()) {
//			System.out.println("request failed");
			throw new Exception("请求失败");
		}
		return response;
	}


	/**
	 *
	 * @param url
	 * @param data
	 * @param headerMap
	 * @param timeout 单位秒
	 * @return
	 * @param <T>
	 * @throws Exception
	 */
	public static <T> Response postJsonBody(String url, T data, Map<String,String> headerMap,Integer timeout) throws Exception {
		Request.Builder builder = new Request.Builder()
				.url(url);

		if(data!=null){
			// POST方式发送JSON数据
//		String json = "{\"username\":zhangsan,\"password\":\"123456\"}";

			String json = objectMapper.writeValueAsString(data);
			log.debug(json);
//		构建json请求头
			RequestBody body = RequestBody.create( json,MediaType.parse("application/json"));
			builder.post(body);
		}

		// 遍历Map并将头部信息添加到请求构建器中
		if(headerMap!=null){
			headerMap.forEach(builder::addHeader); //等价headerMap.forEach((key, value) -> builder.addHeader(key, value));
		}

		Request request = builder.build();

		OkHttpClient okHttpClient = new OkHttpClient.Builder()
				.connectTimeout(timeout, TimeUnit.SECONDS) // 连接超时时间
				.readTimeout(timeout, TimeUnit.SECONDS)     // 读取超时时间
				.writeTimeout(timeout, TimeUnit.SECONDS) // 写入超时时间;
				.build();


		Call call = okHttpClient.newCall(request);
		Response response = null;
		response = call.execute();


		if (!response.isSuccessful()) {
//			System.out.println("request failed");
			throw new Exception("请求失败");
		}
		return response;
	}

}
